import re

from django.conf import settings
from django_redis import get_redis_connection
from rest_framework import serializers


from oauth.models import OAuthQQUser
from users.models import User
from itsdangerous import TimedJSONWebSignatureSerializer as TJS


class OauthSerializer(serializers.ModelSerializer):
    access_token = serializers.CharField(write_only=True)
    sms_code = serializers.CharField(max_length=4,min_length=4,write_only=True)
    token = serializers.CharField(read_only=True)
    """
    虽然我们可根据模型类⾃自 动⽣生成，但是我么需要显示的按照我 们的限制条件定义，根据模型类⽣生成 的条件中会有唯⼀一值判断，不不符合业 务逻
    """
    mobile = serializers.CharField(max_length=11,write_only=True)
    username = serializers.CharField(read_only=True)

    class Meta:
        model = User
        fields = ('mobile', 'password', 'sms_code', 'access_token', 'id', 'username', 'token')
        extra_kwargs = {
            "password":{
                'max_length': 20,
                'min_length': 8,
                'write_only': True
            }
        }

    def validate_mobile(self,value):
        if not re.match(r"^1[3-9]\d{9}$",value):
            raise serializers.ValidationError("电话格式不正确")
        return value

    def validate(self,data):

        conn = get_redis_connection("sms_code")
        real_sms_code = conn.get("sms_code_%s" %data["mobile"])
        if not real_sms_code:
            raise serializers.ValidationError('验证码失效')

        if real_sms_code.decode() != data["sms_code"]:
            raise serializers.ValidationError("验证码错误")

        tjs = TJS(settings.SECRET_KEY,300)

        try:
            data_access_token = tjs.loads(data["access_token"])
        except Exception as e:
            print(e)
            raise serializers.ValidationError('错误的access—token')

        openid = data_access_token.get("openid")

        if openid is None:
            raise serializers.ValidationError("access token　过期")

        data["openid"] = openid

        # 验证User是否存在
        try:
            user = User.objects.get(mobile=data.get("mobile"))
        except:
            return data
        else:
            if not user.check_password(data["password"]):
                raise serializers.ValidationError("密码错误")
            data["user"]=user
            return data


    def create(self, validated_data):
        user = validated_data.get("user")
        print(user)
        if not user:
            user = User.objects.create(
                username=validated_data['mobile'],
                password=validated_data['password'],
                mobile=validated_data['mobile'],
            )

        OAuthQQUser.objects.create(
            user = user,
            openid = validated_data["openid"],
        )
        return user

